layui.define((exports) => {
    "use strict";

    let $ = layui.$
    let layer = layui.layer
    let form = layui.form

    let options = {
        QUERY_API: "",
        UPDATE_API: "",
        CREATE_API: "",
        DELETE_API: "",
        BUILD_API: "",

        CREATE_FIELD_API: "",
        UPDATE_FIELD_API: "",
        DELETE_FIELD_API: "",

    }

    /**
     * 获取表
     * @param {string} url 
     * @param {object} params 
     */
    let getTable = (url, params) => {
        $.post(url, params, function (res) {
            if (res.code == 0) {
                let html = ""
                res.data.forEach(item => {
                    html += `<tr>
                    <td>
                        <input type="checkbox" data-id="${item.table}" lay-filter="checkThis">
                    </td>
                    <td>
                        <a href="javascript:;" kb-event="children" data-id="${item.table}">
                            <i class="layui-icon layui-icon-triangle-r"></i>
                        </a>
                        ${item.table}
                    </td>
                    <td>${item.comment}</td>
                    <td>${item.rows}</td>
                    <td>
                        <div class="kb-btn-container">
                            <button type="button" class="layui-btn layui-btn-primary layui-border layui-btn-xs" kb-event="build" data-id="${item.table}">生成</button>
                            <button type="button" class="layui-btn layui-bg-orange layui-btn-xs" kb-event="edit" data-id="${item.table}">编辑</button>
                            <button type="button" class="layui-btn layui-bg-red layui-btn-xs" kb-event="delete" data-id="${item.table}">删除</button>
                        </div>
                    </td>
                </tr>`
                })
                $(".kb-table-body").html(html)
                form.render()
            } else {
                layer.msg(res.msg)
            }
        })

    }

    /**
     * 窗口函数
     * @param {string} url 
     */
    let open_fun = (url) => {
        layer.open({
            type: 2,
            area: ['800px', '600px'],
            title: '信息',
            shade: 0.001, // 遮罩透明度
            shadeClose: true, // 点击遮罩区域，关闭弹层
            maxmin: true, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: url,
            btn: ['确定', '重置'],
            yes: function (index, layero, that) {
                let submit = layer.getChildFrame(`button[type="submit"]`, index)
                submit.click()
                return false
            },
            btn2: function (index, layero, that) {
                let reset = layer.getChildFrame(`button[type="reset"]`, index)
                reset.click()
                return false
            }
        });
    }

    /**
     * 删除表函数
     * @param {Array|string} id 
     */
    let delete_fun = (url, id) => {
        let index = layer.load(1)
        $.get(url, { id }, function (res) {
            if (res.code == 0) {
                layer.msg(res.msg, { icon: 1 }, function () {
                    window.location.reload()
                })
            } else {
                layer.msg(res.msg)
            }
            layer.close(index)
        })
    }

    // 字段获取
    $("body").delegate(`[kb-event="children"]`, "click", function () {
        let then = $(this)
        let table = then.attr("data-id")
        if (then.find("i").attr("class") === "layui-icon layui-icon-triangle-r") {
            then.find("i").attr("class", "layui-icon layui-icon-triangle-d")
            if ($(`#${table}`).length === 0) {
                $.post(options.QUERY_API, { type: "fields", table }, function (res) {
                    if (res.code == 0) {
                        let html = `<tr id="${table}">
                        <td colspan="5">
                            <div class="kb-btn-container">
                                <button type="button" class="layui-btn layui-bg-blue layui-btn-xs" kb-event="insert-field">添加字段</button>
                            </div>
                            <table class="layui-table">
                                <thead>
                                    <tr>
                                        <th>字段名</th>
                                        <th>类型</th>
                                        <th>默认</th>
                                        <th>备注</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>`
                        res.data.forEach(item => {
                            let btn = `<button type="button" class="layui-btn layui-bg-orange layui-btn-xs" kb-event="edit-field" data-id="${item.field}">编辑</button>
                            <button type="button" class="layui-btn layui-bg-red layui-btn-xs" kb-event="delete-field" data-id="${item.field}">删除</button>`
                            if (item.field == "id") {
                                btn = ""
                            }
                            html += `<tr>
                                <td>${item.field}</td>
                                <td>${item.type}</td>
                                <td>${item.default}</td>
                                <td>${item.comment}</td>
                                <td>
                                    <div class="kb-btn-container">
                                        ${btn}
                                    </div>
                                </td>
                            </tr>`
                        })
                        html += ` </tbody></table></td></tr>`;
                        then.parent().parent().after(html)
                    } else {
                        layer.msg(res.msg)
                    }
                })
            } else {
                $(`#${table}`).show()
            }
        } else {
            $(this).find("i").attr("class", "layui-icon layui-icon-triangle-r")
            $(`#${table}`).hide()
        }
    })

    // 添加表
    $("body").delegate(`[kb-event="create"]`, "click", function () {
        open_fun(options.CREATE_API)
    })

    // 编辑表
    $("body").delegate(`[kb-event="edit"]`, "click", function () {
        let id = $(this).attr("data-id");
        open_fun(options.UPDATE_API + "?id=" + id)
    })

    // 删除表
    $("body").delegate(`[kb-event="delete"]`, "click", function () {
        let id = $(this).attr("data-id");
        layer.confirm('确定要操作吗？', { icon: 2 }, function () {
            delete_fun(options.DELETE_API, id)
        });
    })

    // 批量删除
    $("body").delegate(`[kb-event="delete-all"]`, "click", function () {
        let id = JSON.parse($(this).attr("data-id"));
        if (id.length < 1) {
            layer.msg("请选择数据")
        } else {
            layer.confirm('确定要操作吗？', { icon: 2 }, function () {
                delete_fun(options.DELETE_API, id)
            });
        }
    })

    // 勾选
    form.on('checkbox(checkThis)', function (data) {
        let id = $(data.elem).attr("data-id")
        let object = JSON.parse($(`[kb-event="delete-all"]`).attr("data-id"))
        if (data.elem.checked) {
            object.push(id)
            $(`[kb-event="delete-all"]`).attr("data-id", JSON.stringify(object))
        } else {
            object.splice(object.indexOf(id), 1)
            $(`[kb-event="delete-all"]`).attr("data-id", JSON.stringify(object))
        }
    })

    // 全部勾选开关
    form.on('checkbox(checkAll)', function (data) {
        let object = JSON.parse($(`[kb-event="delete-all"]`).attr("data-id"))
        if (data.elem.checked) {
            $("input[type='checkbox']").prop("checked", true)
            $(`input[lay-filter="checkThis"]`).each(function (k, v) {
                let id = $(v).attr("data-id")
                object.push(id)
            })
        } else {
            object = []
            $("input[type='checkbox']").prop("checked", false)
        }
        $(`[kb-event="delete-all"]`).attr("data-id", JSON.stringify(object))
        form.render('checkbox');
    })

    // 添加字段
    $("body").delegate(`[kb-event="insert-field"]`, "click", function () {
        let id = $(this).parent().parent().parent().attr("id")
        open_fun(options.CREATE_FIELD_API + "?id=" + id)
    })

    // 修改字段
    $("body").delegate(`[kb-event="edit-field"]`, "click", function () {
        let id = $(this).parent().parent().parent().parent().parent().parent().parent().attr("id")
        let ab = $(this).attr("data-id")
        open_fun(options.UPDATE_FIELD_API + "?id=" + id + "&ab=" + ab)
    })

    // 删除字段
    $("body").delegate(`[kb-event="delete-field"]`, "click", function () {
        let id = $(this).parent().parent().parent().parent().parent().parent().parent().attr("id")
        let ab = $(this).attr("data-id")
        layer.confirm('确定要操作吗？', { icon: 2 }, function () {
            delete_fun(options.DELETE_FIELD_API + "?id=" + id + "&ab=" + ab, {})
        });
    })

    // 生成表单
    $("body").delegate(`[kb-event="build"]`, "click", function () {
        let id = $(this).attr("data-id");
        open_fun(options.BUILD_API + "?id=" + id)
    })

    let mysql = {
        /**
         * sql表渲染
         * @param {string} url 
         * @param {object} params 
         */
        render: function (config) {
            options.QUERY_API = config.QUERY_API || options.QUERY_API
            options.UPDATE_API = config.UPDATE_API || options.UPDATE_API
            options.CREATE_API = config.CREATE_API || options.CREATE_API
            options.DELETE_API = config.DELETE_API || options.DELETE_API
            options.BUILD_API = config.BUILD_API || options.BUILD_API

            options.CREATE_FIELD_API = config.CREATE_FIELD_API || options.CREATE_FIELD_API
            options.UPDATE_FIELD_API = config.UPDATE_FIELD_API || options.UPDATE_FIELD_API
            options.DELETE_FIELD_API = config.DELETE_FIELD_API || options.DELETE_FIELD_API



            getTable(options.QUERY_API, { type: "table" })
        }
    }

    exports('mysql', mysql);
})